# -*- coding: utf-8 -*-
"""
@Time ： 2024/6/7 11:07
@Auth ： 李天天
"""
import subprocess


def run_adb_command(command):
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    if result.returncode != 0:
        raise Exception(f"Command failed: {command}\n{result.stderr}")
    return result.stdout.strip()


def get_process_ids(device_id, package_name):
    command = f"adb -s {device_id} shell ps | grep {package_name}"
    output = run_adb_command(command)
    pids = []
    for line in output.splitlines():
        parts = line.split()
        if len(parts) > 1:
            pids.append(parts[1])
    return pids


def get_ports(device_id, pid):
    tcp_command = f"adb -s {device_id} shell cat /proc/{pid}/net/tcp"
    udp_command = f"adb -s {device_id} shell cat /proc/{pid}/net/udp"

    tcp_output = run_adb_command(tcp_command)
    udp_output = run_adb_command(udp_command)

    tcp_ports = parse_ports(tcp_output)
    udp_ports = parse_ports(udp_output)

    return tcp_ports, udp_ports


def get_ports_ipv6(device_id, pid):
    tcp_command = f"adb -s {device_id} shell cat /proc/{pid}/net/tcp6"
    udp_command = f"adb -s {device_id} shell cat /proc/{pid}/net/udp6"

    tcp_output = run_adb_command(tcp_command)
    udp_output = run_adb_command(udp_command)

    tcp_ports = parse_ports(tcp_output)
    udp_ports = parse_ports(udp_output)

    return tcp_ports, udp_ports


def parse_ports(net_output):
    ports = []
    for line in net_output.splitlines()[1:]:
        parts = line.split()
        if len(parts) > 1:
            local_address = parts[1]
            port_hex = local_address.split(":")[1]
            port = int(port_hex, 16)
            ports.append(port)
    return ports


def main():
    device_id = input("Enter the device ID: ")
    package_name = input("Enter the package name: ")

    try:
        pids = get_process_ids(device_id, package_name)
        if not pids:
            print(f"No processes found for package {package_name}")
            return

        for pid in pids:
            tcp_ports, udp_ports = get_ports(device_id, pid)
            print(f"PID: {pid}")
            print(f"TCP Ports: {tcp_ports}")
            print(f"去重-TCP Ports: {set(tcp_ports)}")

            print(f"UDP Ports: {udp_ports}")
            print(f"去重-UDP Ports: {set(udp_ports)}")
    except Exception as e:
        print(f"An error occurred: {e}")


def main_copy(device_id, package_name):
    try:
        pids = get_process_ids(device_id, package_name)
        if not pids:
            print(f"No processes found for package {package_name}")
            return

        for pid in pids:
            tcp_ports, udp_ports = get_ports(device_id, pid)
            print(f"PID: {pid}")
            print(f"去重后-TCP Ports: {list(set(tcp_ports))}")
            print(f"去重后-UDP Ports: {list(set(udp_ports))}")
            tcp_ports, udp_ports = get_ports_ipv6(device_id, pid)
            print(f"去重后-TCP6 Ports: {list(set(tcp_ports))}")
            print(f"去重后-UDP6 Ports: {list(set(udp_ports))}")

    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    print("===中心端 端口占用情况===")
    main_copy("af4ba435", "com.arcvideo.sdk.demo")
    print("\n")
    print("===左后 端口占用情况===")
    main_copy("HGR3VD3Y", "com.arcvideo.sdk.demo")
    print("\n")
    print("===右后 端口占用情况===")
    main_copy("W3VBB23215208595", "com.arcvideo.sdk.demo")
    print("\n")
